//
//  UIViewController+HKLeak.m
//  HKUtilities
//
//  Created by 胡锦涛 on 2020/4/5.
//  Copyright © 2020 胡锦涛. All rights reserved.
//

#import "UIViewController+HKLeak.h"
#import "UIViewController+HKExtension.h"
#import <objc/runtime.h>
const char* deallocKey = "isDeallocDisAppear";
@implementation UIViewController (HKLeak)
+(void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self hk_changeSel:@selector(viewDidDisappear:) toSel:@selector(leak_viewDidDisappear:)];
        [self hk_changeSel:@selector(dismissViewControllerAnimated:completion:) toSel:@selector(leak_dismissViewControllerAnimated:completion:)];
        [self hk_changeSel:@selector(viewWillAppear:) toSel:@selector(leak_viewWillAppear:)];
    });
}
///进入界面，初始化标志
-(void)leak_viewWillAppear:(BOOL)animated{
    [self leak_viewWillAppear:animated];
    self.isHKDisappear = NO;
}
///dismiss时机扑捉并设置标志
-(void)leak_dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion{
    [self leak_dismissViewControllerAnimated:flag completion:completion];
    self.isHKDisappear = YES;
}
///即将释放时调用延时任务
- (void)leak_viewDidDisappear:(BOOL)animated{
    [self leak_viewDidDisappear:animated];
    BOOL isDeallocDis = self.isHKDisappear;
    if (isDeallocDis) {
        [self willDealloc];
    }
}
///延时处理，如果释放，不会走 [strongSelf showMsg:msg];
- (void) willDealloc{
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {
            NSString* msg = [NSString stringWithFormat:@"%@__存在内存泄漏",[weakSelf class]];
            ///泄漏提示
           // [(UIViewController*)strongSelf showAlertWithTitle:@"内存泄露了" message:msg confirmTitle:@"好的" handler:nil];
        }
    });
}
///动态设置标志属性
-(void)setIsHKDisappear:(BOOL)isHKDisappear{
    objc_setAssociatedObject(self, &deallocKey, @(isHKDisappear), OBJC_ASSOCIATION_RETAIN);
}
///动态获取标志属性的值
-(BOOL)isHKDisappear{
    
    return ((NSNumber*)objc_getAssociatedObject(self, &deallocKey)).boolValue;
}


@end
